<template>
  <div class="flex flex-col min-h-screen bg-weather-primary">
    <header class="bg-weather-primary shadow-lg sticky top-0 z-10">
      <nav class="container flex flex-col sm:flex-row items-center gap-4 text-white py-6">
        <a href="/weather" class="router-link-active router-link-exact-active">
          <div class="flex items-center gap-3">
            <span class="fa-solid fa-sun text-2xl"></span>
            <p class="text-2xl">新中地天气</p>
          </div>
        </a>
        <div class="flex gap-4 items-center" v-if="livesWeather.lives">
          <h4 class="text-lg">{{ livesWeather.lives[0].city }}</h4>
          <span class="text-sm"
            >实时天气：{{ livesWeather.lives[0].weather }}
            {{ livesWeather.lives[0].temperature }}°C</span
          >
          <span class="text-sm"
            >{{ livesWeather.lives[0].winddirection }}风{{ livesWeather.lives[0].windpower }}级</span
          >
        </div>
        <div class="flex gap-3 flex-1 justify-end">
          <i
            class="fixed fa-solid fa-circle-info text-xl hover:text-weather-secondary cursor-pointer duration-1000"
            @click="tipClick"
          ></i>
        </div>
      </nav>
    </header>
    <main class="container text-white">
      <div class="pt-4 mb-8 relative">
        <input
          v-model="cityName"
          type="text"
          placeholder="请输入城市名称"
          class="py-2 px-1 w-full bg-transparent border-b focus:border-weather-secondary focus:outline-none focus:shadow-md"
        />
        <ul
          class="absolute bg-weather-secondary text-white w-full shadow-md py-2 px-1 top-[62px]"
          style="display: none"
          ref="ul"
        >
          <p style="display: none">对不起网络似乎除了点问题 请稍后再查询</p>
          <p style="display: none" ref="search">似乎没有找到你查找的城市</p>
          <li
            class="py-2 cursor-pointer"
            v-for="(item, index) in citysArr"
            :key="index"
            ref="li"
            @click="handleClick(item)"
          >
            {{ item }}
          </li>
        </ul>
      </div>
      <div
        ref="citysData"
        v-if="renderCitys.length > 0"
        class="mt-10 max-h-[300px] scrollbar-thin hover:scrollbar-thumb-blue-300"
      >
        <div
          @mouseover="handleMouseOver(index)"
          @mouseout="handleMouseOut(index)"
          v-for="(item, index) in renderCitys"
          :key="index"
          class="flex justify-between"
        >
          <div
            ref="div"
            class="mb-4 bg-weather-secondary py-2 px-4 flex justify-between cursor-pointer w-full duration-300"
          >
            <h3>{{ item[0].city }}</h3>
            <span>{{ item[0].temperature }}度</span>
          </div>
          <div class="flex mb-4 gap-2" style="display: none" ref="divButton">
            <button class="bg-yellow-500 text-center w-[80px]" @click="handleCheck(index)">
              查看</button
            ><button class="bg-yellow-500 text-center w-[80px]" @click="handleDelete(index)">
              删除
            </button>
          </div>
        </div>
      </div>
      <h2 v-else class="text-center duration-200" ref="h2">
        暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
      </h2>

      <h2 class="mt-6">近期天气</h2>
      <div class="bg-weather-secondary px-12 pt-10 mt-2 rounded">
        <div class="flex gap-6">
          <template v-for="(item, index) in forecastArr" :key="index">
            <div class="flex flex-col flex-1 text-center gap-4" v-if="forecastArr.length">
              <span>{{ item.day }}</span
              >{{ item.date }} <span></span><span>{{ item.dayweather }}</span
              ><span>风力 {{ item.daypower }}级</span>
            </div>
          </template>
        </div>
        <div
          class="weathercanvas h-40 mt-10"
          _echarts_instance_="ec_1719988101478"
          style="user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0)"
        >
          <div
            style="
              position: relative;
              width: 1120px;
              height: 160px;
              padding: 0px;
              margin: 0px;
              border-width: 0px;
              cursor: default;
            "
          >
            <v-chart :option="options1" autoresize />
          </div>
        </div>
      </div>
    </main>
    <div
      class="fixed z-20 w-full bg-black bg-opacity-30 h-screen top-0 left-0 flex justify-center px-8 text-black"
      style="display: none"
      ref="tip"
    >
      <div class="p-4 bg-white self-start mt-32 max-w-screen-md">
        <h2>关于:</h2>
        <p class="text-xs mb-4">这个应用可以用来追踪你选择城市的当前天气</p>
        <h2>如何使用:</h2>
        <p class="text-xs mb-4">
          1.点击搜索框输入你希望追踪的城市<br />
          2.在搜索结果中选中一个城市，你将获取当地最新的天气<br />
          3.点击右侧的＋号可以将追踪城市的天气情况保存在首页
        </p>
        <h2>移除城市:</h2>
        <p class="text-xs">如果你不想在首页关注某个城市,可以通过底部的按钮删<br />除它</p>
        <button class="text-white mt-8 bg-weather-primary py-2 px-6 text-xs" @click="handleClose">
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import _ from 'lodash';
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useWeatherStore } from '@/stores/index'
import { ref, onMounted, watch } from 'vue'
const {
  getCodeByCityName,
  getForecasts,
  searchCity,
  renderIndexchart,
  getForecastArr,
  getCode,
  getWeather,
  getInfoCity,
  getCity,
  render
} = useWeatherStore()
const router = useRouter()
const { cityName, options1, forecastArr, livesWeather, citys, renderCitys,cityList } =
  storeToRefs(useWeatherStore())
const ul = ref(null)
const li = ref(null)
const search = ref(null)
const h2 = ref(null)
const tip = ref(null)
const div = ref(null)
const divButton = ref(null)
const citysArr = ref([])
const citysData = ref(null)
// const forecastArr = ref([])
//显示提示框
const tipClick = () => {
  //移除display属性
  tip.value.removeAttribute('style')
}
//关闭提示框
const handleClose = () => {
  //添加display属性
  tip.value.style.display = 'none'
}
//处理搜索输入事件的函数
// _.debounce(handleSearch,1000)
const handleSearch = async () => {
  const res = await searchCity(cityName.value)
  //   console.log(res)
  if (cityName.value == '') {
    ul.value.style.display = 'none'
    if (h2.value) {
      h2.value.classList.remove('mt-20')
    }
    // if (citys.value.length > 0) {
    //   citysData.value.removeAttribute('style')
    // }
  } else {
    if (res.status == 0) {
      //将li标签的内容清空
      citysArr.value = []
      //将search组件的display样式移除
      search.value.removeAttribute('style')
      //将ul组件的display样式移除
      ul.value.removeAttribute('style')
      //给h2添加样式
      if (h2.value) {
        h2.value.classList.add('mt-20')
      }
      if (citys.value.length > 0) {
        citysData.value.style.display = 'none'
      }
    } else {
      citysArr.value = []
      ul.value.removeAttribute('style')
      search.value.style.display = 'none'
      if (h2.value) {
        h2.value.classList.add('mt-20')
      }
      if (citys.value.length > 0) {
        citysData.value.style.display = 'none'
      }
      citysArr.value.push(res)
    }
  }
}



// console.log(_.debounce)
// console.log(_.debounce)
const handleClick = async (name) => {
  // console.log(name)
  const { geocodes } = await getCodeByCityName(name)
  const code = geocodes[0].adcode
  console.log(geocodes[0].adcode, 'code')
  await getInfoCity(name)
  // console.log(res,'res')
  router.push({
    name: 'weatherInfo',
    params: {
      code: code,
      name: name
    }
  })
}

const handleMouseOver = (i) => {
  // div.value.classList.add('w-8/12')
  // divButton.value.removeAttribute('style')
  // console.log(i)
  div.value.map((item, index) => {
    if (index == i) {
      // console.log(item,'item')
      item.classList.add('w-3/4')
      divButton.value.map((item, index) => {
        if (index == i) {
          item.removeAttribute('style')
        }
      })
    }
  })
}
const handleMouseOut = (i) => {
  // div.value.classList.remove('w-8/12')
  // divButton.value.style.display = 'none'
  div.value.map((item, index) => {
    if (index == i) {
      // console.log(item, 'item')
      item.classList.remove('w-3/4')
      divButton.value.map((item, index) => {
        if (index == i) {
          item.style.display = 'none'
        }
      })
    }
  })
}
//实现查看详情
const handleCheck = (i) => {
  console.log(i)
  console.log(div.value, 'div')
  div.value.map(async (item, index) => {
    if (index == i) {
      const name = item.firstChild.innerHTML
      const { geocodes } = await getCodeByCityName(name)
      const code = geocodes[0].adcode
      console.log(geocodes[0].adcode, 'code')
      await getInfoCity(name)
      // console.log(res,'res')
      router.push({
        name: 'weatherInfo',
        query: {
          search: name
        },
        params: {
          code: code
        }
      })
    }
  })
}
//实现删除
const handleDelete = async (i) => {
  await render()
  console.log(i, 'i')
  getCity()
  citys.value.splice(i, 1)
  console.log(citys.value,'citys')
  localStorage.setItem('cityList', JSON.stringify(citys.value))
  renderCitys.value.splice(i, 1)
}

watch(cityName, async (newVal) => {
  console.log(newVal, 'newVal')
  // console.log(newVal,"res")
  await getCodeByCityName(cityName.value)
  await getForecasts(cityName.value)
  //   console.log(res, 'res')
  await searchCity(cityName.value)
  // console.log(citysArr.value)
  handleSearch()
  // console.log(cityName.value,"cityName")
  // await searchCity()
})

onMounted(async () => {
  getCity()
  // console.log(citys.value, 'citys')
  await renderIndexchart('')
  getForecastArr()
  getCode('')
  await getWeather('')
  await render()
})
</script>

<style></style>
